import { NavBar, DatePicker } from 'antd-mobile'
import { useMemo, useState, useEffect } from 'react'
import './index.scss'
import classNames from 'classnames';
//时间格式化
import dayjs from 'dayjs';
import { useSelector } from 'react-redux';
import _ from 'lodash';
import DailyBill from './components/DayBill/index.js'

const Month = () => {
    //按月做数据分组
    const billList = useSelector(state => state.bill.billList)
    //数据二次处理
    const monthGroup = useMemo(() => {
        //return出去计算之后的值
        //以时间作为分组条件，时间作为生成对象的key
        return _.groupBy(billList, (item) => dayjs(item.date).format("YYYY-MM"))
    }, [billList])   //依赖项，billList发生变化时重新分组

    //控制弹窗的打开和关闭，数据驱动视图变化
    const [dateVisible, setDateVisible] = useState(false);
    //控制时间显示
    const [currentDate, setCurrentDate] = useState(() => {
        return dayjs(new Date()).format("YYYY-MM")
    })

    //从按月分组数据中找到对应数组
    const [currentMonthList, setCurrentMonthList] = useState([])
    //基于数组做计算，useMemo用于数据的再加工
    const monthResult = useMemo(() => {
        // 当currentMonthList为空时返回0值，防止filter方法报错
        if (currentMonthList.length === 0) {
            return { pay: 0, income: 0, total: 0 }
        }
        //支出 / 收入 / 结余
        //过滤出对应类型记录并使用reduce方法累加
        const pay = currentMonthList.filter(item => item.type === 'pay').reduce((a, c) => a + c.money, 0)
        const income = currentMonthList.filter(item => item.type === 'income').reduce((a, c) => a + c.money, 0)
        return {
            pay,
            income,
            //支出为负数，收入为正数
            total: pay + income
        }
    }, [currentMonthList])

    //初始化时把当前月的统计数据显示出来
    useEffect(() => {
        const nowDate = dayjs(new Date()).format("YYYY-MM")
        //边界值控制
        setCurrentMonthList(monthGroup[nowDate] || []) // 添加空数组默认值
    }, [monthGroup])

    //确认回调
    const onConfirm = (date) => {
        setDateVisible(false);
        //其他逻辑
        const formatDate = dayjs(date).format("YYYY-MM")
        setCurrentDate(formatDate)
        // 添加空数组默认值
        setCurrentMonthList(monthGroup[formatDate] || [])
    }

    //当前月按照日分组
    //return值含日期列表和账单分组数据
    const dayGroup = useMemo(() => {
        const groupData = _.groupBy(currentMonthList, (item) => dayjs(item.date).format("YYYY-MM-DD"))
        const keys = Object.keys(groupData)
        return {
            groupData,
            keys
        }
    }, [currentMonthList])   //依赖项，currentMonthList发生变化时重新分组
    return (
        <div className="monthlyBill">
            <NavBar className="nav" backArrow={false}>
                月度收支
            </NavBar>
            <div className="content">
                <div className="header">
                    {/* 时间切换区域 */}
                    <div className="date" onClick={() => setDateVisible(true)}>
                        <span className="text">
                            {/* 对象无法直接使用，拼接空串转化为字符串 */}
                            {currentDate + ''}月账单
                        </span>
                        {/* 思路：根据当前弹框打开的状态控制expand类名是否存在 */}
                        {/* <span className={classNames('arrow', {expand: dateVisible})} /> */}
                        <span className={classNames('arrow', dateVisible && 'expand')} />
                    </div>
                    {/* 统计区域 */}
                    <div className='twoLineOverview'>
                        <div className="item">
                            <span className="money">{monthResult.pay.toFixed(2)}</span>
                            <span className="type">支出</span>
                        </div>
                        <div className="item">
                            <span className="money">{monthResult.income.toFixed(2)}</span>
                            <span className="type">收入</span>
                        </div>
                        <div className="item">
                            <span className="money">{monthResult.total.toFixed(2)}</span>
                            <span className="type">结余</span>
                        </div>
                    </div>
                    {/* 时间选择器 */}
                    <DatePicker
                        className="kaDate"
                        title="记账日期"
                        precision="month"
                        visible={dateVisible}
                        max={new Date()}
                        closeOnMaskClick={true}
                        onCancel={() => setDateVisible(false)}
                        onConfirm={onConfirm}
                    />
                </div>
                {/* 单日统计列表 */}
                {dayGroup.keys.length > 0 && dayGroup.keys.map((key) => {
                    return <DailyBill key={key} date={key} billList={dayGroup.groupData[key]} />
                })}
            </div>
        </div >
    )
}

export default Month